package indi.mozping.concurrentutil.semaphore;

import indi.mozping.tools.SleepTools;

import java.util.Date;
import java.util.concurrent.Semaphore;

/**
 * @author by mozping
 * @Classname Park
 * @Description TODO
 * @Date 2019/5/28 11:43
 */
public class Park {

    //初始化5代表有5个车位
    static Semaphore semaphore = new Semaphore(5);


    //Car线程模拟车辆去停车
    static class Car implements Runnable {


        @Override
        public void run() {
            try {
                //1.开始停车，先获取许可(相当于获取一个车位)
                semaphore.acquire();
                //2.模拟停车3秒钟
                System.out.println(Thread.currentThread().getName() + " 开始准备停车,剩余车位是: " + semaphore.availablePermits() + " -- " + new Date());
                SleepTools.randomSecond(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //3.停车完毕释放(归还许可，相当于释放车位)
                semaphore.release();
                System.out.println(Thread.currentThread().getName() + " 线程停车完毕,剩余车位是: " + semaphore.availablePermits() + " -- " + new Date());

            }
        }
    }


    public static void main(String[] args) {

        //模拟10辆车去停车，只有5个车位，需要同步
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new Car(), "[Car-" + (i + 1) + "]");
            thread.start();
        }


    }
}